package controllers

import (
    "gouniapp/configs"
	"fmt"
	"net/http"
	"github.com/gin-gonic/gin"
)

// 获取模板列表
func GetPicTemplateList(c *gin.Context) {
	var req configs.FormQuery
	if err := c.ShouldBindQuery(&req); err != nil {
		JsonResponse(c, http.StatusBadRequest, "参数错误", nil)
		return
	}

	query := configs.DB.Model(&configs.PicTemplate{})
	if req.Search != "" {
		query = query.Where("name LIKE ?", fmt.Sprintf("%%%s%%", req.Search))
	}

	var total int64
	if err := query.Count(&total).Error; err != nil {
		JsonResponse(c, http.StatusInternalServerError, "查询失败", nil)
		return
	}

	var templates []configs.PicTemplate
	if err := query.Scopes(configs.Paginate(req.Page, req.PageSize)).Order("id DESC").Find(&templates).Error; err != nil {
		JsonResponse(c, http.StatusInternalServerError, "获取数据失败", nil)
		return
	}

	JsonResponse(c, http.StatusOK, "成功", gin.H{
		"items": templates,
		"total": total,
	})
}

// 获取指定页面模板
func GetPicTemplateDetail(c *gin.Context) {
	id := c.Param("id")
	var template configs.PicTemplate
	if err := configs.DB.First(&template, id).Error; err != nil {
		JsonResponse(c, http.StatusNotFound, "模板不存在", nil)
		return
	}
	JsonResponse(c, http.StatusOK, "获取成功", template)
}

// 创建模板
func AddPicTemplate(c *gin.Context) {
	var template configs.PicTemplate
	if err := c.ShouldBindJSON(&template); err != nil {
		JsonResponse(c, http.StatusBadRequest, "数据解析失败", nil)
		return
	}

	if err := configs.DB.Create(&template).Error; err != nil {
		JsonResponse(c, http.StatusInternalServerError, "创建失败", nil)
		return
	}

	JsonResponse(c, http.StatusOK, "创建成功", template)
}

// 更新模板
func UpdatePicTemplate(c *gin.Context) {
	id := c.Param("id")
	var template configs.PicTemplate
	if err := configs.DB.First(&template, id).Error; err != nil {
		JsonResponse(c, http.StatusNotFound, "模板不存在", nil)
		return
	}

	if err := c.ShouldBindJSON(&template); err != nil {
		JsonResponse(c, http.StatusBadRequest, "数据解析失败", nil)
		return
	}

	if err := configs.DB.Save(&template).Error; err != nil {
		JsonResponse(c, http.StatusInternalServerError, "更新失败", nil)
		return
	}

	JsonResponse(c, http.StatusOK, "更新成功", template)
}

// 删除模板
func DeletePicTemplate(c *gin.Context) {
	id := c.Param("id")
	if err := configs.DB.Delete(&configs.PicTemplate{}, id).Error; err != nil {
		JsonResponse(c, http.StatusInternalServerError, "删除失败", nil)
		return
	}
	JsonResponse(c, http.StatusOK, "删除成功", nil)
}